import { Component, Inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { REST_ADDR, REST_URL } from 'src/app/app.component';
import { AppSettings } from 'src/app/configs/app-settings';
import { AppSettingsService } from 'src/app/services/app-settings.service';
import { AppService } from 'src/app/services/app.service';
import { LoginInfoService } from 'src/app/services/login-info.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  isAuthenticated = false;
  checkSessionChanged$?: Observable<boolean>;
  checkSessionChanged?: boolean;


  settings!: AppSettings;

  public isLoggedIn = false;
  constructor(
    public _service: AppService,
    private _router: Router,
    private _loginInfo: LoginInfoService,
    private _appSettings: AppSettingsService,
    @Inject(REST_URL) private baseUrl: string,
    @Inject(REST_ADDR) private serverAddr: string){
      this.settings = this._appSettings.getSettings();

    }

    ngOnInit() {
      console.log(`Home inited with :${window.location.href}`);
      
      this.isLoggedIn = this._service.checkCredentials();    
      const i = window.location.href.indexOf('code');
      if (!this.isLoggedIn && i == -1) {
        console.log('No code, redirect to oauth2/authorize');
        window.location.href = 
//        'http://localhost:20110/oauth2/authorize?client_id=messaging-client&response_type=code&scope=openid&redirect_uri=http%3A%2F%2Flocalhost%3A820110%2Flogin%2Foauth2%2Fcode%2Fmessaging-client-oidc';
        this.baseUrl + `oauth2/authorize?client_id=${this.settings.clientId}&response_type=code&scope=all&redirect_uri=http%3A%2F%2F${this.serverAddr}%3A4200`;
      } else if(!this.isLoggedIn && i != -1) {
        console.log(`to retrive token with ${window.location.href.substring(i + 5)}`);
        this._service.retrieveToken(window.location.href.substring(i + 5));
      } else {
        console.log('logged in home');

        this._router.navigateByUrl('/menu');
      }
    }
   
    logout() {
      this._service.logout();
    }
}
